package cn.jack.lib_common.flutter.base

import android.content.Context
import io.flutter.embedding.engine.loader.FlutterLoader
import java.io.File

/**
 * @创建者 Jack
 * @创建时间 2024-09-08 23:36
 * @描述
 */
class CustomFlutterLoader : FlutterLoader() {
    companion object {
        const val UPDATE_SO = "libappupdate.so"
        private var instance: CustomFlutterLoader? = null
            get() {
                if (field == null) {
                    field = CustomFlutterLoader()
                }
                return field
            }

        fun get(): CustomFlutterLoader {
            return instance!!
        }
    }

    override fun ensureInitializationComplete(
        applicationContext: Context,
        args: Array<out String>?
    ) {
        val targetSoPath = applicationContext.filesDir //新的so所存放的路径
        val targetSoFile = File(targetSoPath, UPDATE_SO)
        if(targetSoFile.exists()){
            //通过反射的方式将 FlutterLoader aotSharedLibraryName libapp.so替换成新的路径中的so
            val filed = FlutterLoader::class.java.getDeclaredField("aotSharedLibraryName")
            filed.isAccessible = true
            filed[this] = targetSoFile.absolutePath
        }
        super.ensureInitializationComplete(applicationContext, args)
    }
}